package at.fhj.itm11.fotorater.rest;

import java.util.List;
import java.util.logging.Logger;

import javax.faces.bean.RequestScoped;
import javax.inject.Inject;
import javax.validation.Validator;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import at.fhj.itm11.fotorater.model.Category;
import at.fhj.itm11.fotorater.model.Photo;
import at.fhj.itm11.fotorater.service.PhotoViewService;

@Path("/view")
@RequestScoped
public class PhotoViewRestService {

	private final int NUMBEROFPHOTOSPERPAGE = 20;

	@Inject
	private Logger log;

	@Inject
	private Validator validator;

	@Inject
	private PhotoViewService photoService;

	@GET
	@Path("/date/{page:[0-9][0-9]*}")
	@Produces("application/json")
	public List<Photo> getPhotosByDate(@PathParam("page") int page) {
		Delimiters delimiters = new Delimiters(page);

		return photoService.getPhotosByDate(delimiters.getFirstResult(),
				delimiters.getMaxResult());
	}

	@GET
	@Path("/category/{id:[0-9][0-9]*}/{page:[0-9][0-9]*}")
	@Produces("application/json")
	public List<Photo> getPhotosByCategory(@PathParam("id") long id,
			@PathParam("page") int page) {
		Delimiters delimiters = new Delimiters(page);

		return photoService.getPhotosByCategory(id,
				delimiters.getFirstResult(), delimiters.getMaxResult());
	}

	@GET
	@Path("/best/{page:[0-9][0-9]*}")
	@Produces("application/json")
	public List<Photo> getPhotosByLikes(@PathParam("page") int page) {
		Delimiters delimiters = new Delimiters(page);

		return photoService.getPhotosByLikes(delimiters.getFirstResult(),
				delimiters.getMaxResult());
	}

	@GET
	@Path("/worst/{page:[0-9][0-9]*}")
	@Produces("application/json")
	public List<Photo> getPhotosByDislikes(@PathParam("page") int page) {
		Delimiters delimiters = new Delimiters(page);

		return photoService.getPhotosByDislikes(delimiters.getFirstResult(),
				delimiters.getMaxResult());
	}

	@GET
	@Path("/categories")
	@Produces("application/json")
	public List<Category> getCategories() {
		return photoService.getCategoriesOrderedByName();
	}

	private class Delimiters {

		private int firstResult;
		private int maxResult;

		public Delimiters(int page) {
			firstResult = 0;
			maxResult = NUMBEROFPHOTOSPERPAGE;

			if (page > 0) {
				firstResult = page * 10;
				maxResult = firstResult + NUMBEROFPHOTOSPERPAGE - 1;
			}
		}

		public int getFirstResult() {
			return firstResult;
		}

		public int getMaxResult() {
			return maxResult;
		}
	}
}